<template>
    <div class="login">
        <el-form ref="loginform" :model="loginlist" label-width="100px" :rules="rules" class="loginForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginlist.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginlist.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { userLogin } from '../request/api'
export default {
    data() {
        return {
            loginlist: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在2-8', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在6到16个字符', trigger: 'blur'
                    }
                ]
            }
        }
    },
    methods: {
        //封装一个登录事件
        login() {
            this.$refs.loginform.validate((val) => {
                if (val) {
                    // console.log(this.loginlist, 'okkkkk');
                    userLogin(this.loginlist).then(res => {
                        // console.log(res);
                        if (res.code == 200) {
                            this.$message.success(res.msg)
                            // 先存储用户信息
                            this.$store.dispatch('changeUserAction', res.list)
                            this.$router.push('/index')
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        }
    }
}
</script>
<style scoped>
.login {
    width: 100vw;
    height: 100vh;
}

.loginForm {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 400px;
    height: 350px;
    margin: -150px 0 0 -170px;
}
</style>